"use client";

import React, { useState, useEffect } from "react";
import { Spin } from "antd";
import req from "@/libs/request";
import { ApiName, IdKeyLetterKey } from "../../constant";
import "./index.css";

interface AnswerAnalysisProps {
    practiceId: string;
}

interface SubjectItem {
    subjectId: string;
    subjectType: string;
    isCorrect: number;
}

interface OptionItem {
    isCorrect: number;
    optionContent: string;
    optionType: string;
    isAnswer: number;
}

const AnswerAnalysis: React.FC<AnswerAnalysisProps> = ({ practiceId }) => {
    const [subjectList, setSubjectList] = useState<SubjectItem[]>([]);
    const [subjectName, setSubjectName] = useState<string>("");
    const [optionList, setOptionList] = useState<OptionItem[]>([]);
    const [labelNames, setLabelNames] = useState<string[]>([]);
    const [respondAnswer, setRespondAnswer] = useState<string[]>([]);
    const [subjectParse, setSubjectParse] = useState<string>("");
    const [correctAnswer, setCorrectAnswer] = useState<string[]>([]);
    const [currentIndex, setCurrentIndex] = useState<number>(0);
    const [isLoading, setIsLoading] = useState<boolean>(false);

    useEffect(() => {
        getScoreDetail();
    }, []);

    /**
     * 答案解析-获得题目列表
     */
    const getScoreDetail = async () => {
        try {
            setIsLoading(true);
            // TODO: 替换为实际API调用
            const mockData = [
                { subjectId: "1", subjectType: "1", isCorrect: 1 },
                { subjectId: "2", subjectType: "1", isCorrect: 0 },
                { subjectId: "3", subjectType: "1", isCorrect: 1 },
            ];
            setSubjectList(mockData);
            if (mockData.length > 0) {
                await getSubjectDetail(0, mockData[0]);
            }
        } catch (error) {
            console.error("获取题目列表失败:", error);
        } finally {
            setIsLoading(false);
        }
    };

    /**
     * 答案解析-获得答案详情
     */
    const getSubjectDetail = async (
        index: number,
        subjectItem: SubjectItem
    ) => {
        try {
            setIsLoading(true);
            // TODO: 替换为实际API调用
            const mockData = {
                subjectName: "这是一道测试题目",
                optionList: [
                    { isCorrect: 1, optionContent: "选项A", optionType: "A" },
                    { isCorrect: 0, optionContent: "选项B", optionType: "B" },
                    { isCorrect: 0, optionContent: "选项C", optionType: "C" },
                    { isCorrect: 0, optionContent: "选项D", optionType: "D" },
                ],
                labelNames: ["知识点1", "知识点2"],
                respondAnswer: ["A"],
                subjectParse: "这是题目解析",
                correctAnswer: ["A"],
            };

            const respondAnswer = mockData.respondAnswer;
            const optionList = mockData.optionList.map((element) => ({
                ...element,
                isAnswer: respondAnswer.includes(element.optionType) ? 1 : 0,
            }));

            setCurrentIndex(index);
            setSubjectName(mockData.subjectName);
            setOptionList(optionList);
            setLabelNames(mockData.labelNames);
            setRespondAnswer(mockData.respondAnswer);
            setSubjectParse(mockData.subjectParse);
            setCorrectAnswer(mockData.correctAnswer);
        } catch (error) {
            console.error("获取答案详情失败:", error);
        } finally {
            setIsLoading(false);
        }
    };

    const handleOptionChange = (index: number, item: SubjectItem) => () => {
        if (index === currentIndex) return;
        getSubjectDetail(index, item);
    };

    const isRight = correctAnswer.join("") === respondAnswer.join("");

    return (
        <Spin spinning={isLoading}>
            <div className="answer-analysis-container">
                {subjectList.length > 0 && (
                    <div className="answer-analysis-paging">
                        <div className="answer-analysis-paging-tip">
                            每题得分
                        </div>
                        <div className="answer-analysis-paging-list">
                            {subjectList.map((item, index) => (
                                <div
                                    key={`${item.subjectId}_${index}`}
                                    className={`answer-analysis-paging-item ${
                                        item.isCorrect === 1
                                            ? "answer-analysis-right"
                                            : "answer-analysis-error"
                                    } ${currentIndex === index ? "answer-analysis-paging-item-active" : ""}`}
                                    onClick={handleOptionChange(index, item)}
                                >
                                    {index + 1}
                                </div>
                            ))}
                        </div>
                    </div>
                )}
                <div className="answer-analysis-content">
                    <div className="answer-analysis-name">
                        <div className="answer-analysis-name-num">
                            {currentIndex + 1}
                        </div>
                        <div className="answer-analysis-name-text">
                            {subjectName}
                        </div>
                    </div>
                    <div className="answer-analysis-answer">
                        正确答案：
                        {correctAnswer.length > 0
                            ? correctAnswer.map((item, index) => (
                                  <span key={`correct_answer_${index}`}>
                                      {IdKeyLetterKey[item] + " "}
                                  </span>
                              ))
                            : "空"}
                        你的答案：
                        {respondAnswer.length > 0
                            ? respondAnswer.map((item, index) => (
                                  <span key={`respond_answer_${index}`}>
                                      {IdKeyLetterKey[item] + " "}
                                  </span>
                              ))
                            : "空"}
                        <span
                            className={
                                isRight ? "answer-correct" : "answer-wrong"
                            }
                        >
                            &nbsp;({isRight ? "正确" : "错误"})
                        </span>
                    </div>
                    {optionList.length > 0 && (
                        <div className="answer-analysis-option-list">
                            {optionList.map((item, index) => (
                                <div
                                    key={`option_${index}`}
                                    className={`answer-analysis-option-item ${
                                        item.isCorrect === 1
                                            ? "answer-analysis-option-item-right"
                                            : item.isAnswer === 1
                                              ? "answer-analysis-option-item-error"
                                              : ""
                                    }`}
                                    dangerouslySetInnerHTML={{
                                        __html: item.optionContent,
                                    }}
                                />
                            ))}
                        </div>
                    )}
                    {labelNames.length > 0 && (
                        <div className="answer-analysis-points">
                            <div className="answer-analysis-points-tip">
                                本题知识点
                            </div>
                            <div className="answer-analysis-points-list">
                                {labelNames.map((item, index) => (
                                    <div
                                        key={`point_${index}`}
                                        className="answer-analysis-points-item"
                                    >
                                        {item}
                                    </div>
                                ))}
                            </div>
                        </div>
                    )}
                    {subjectParse && (
                        <div className="answer-analysis-parse">
                            <div className="answer-analysis-parse-tip">
                                题目解析
                            </div>
                            <div className="answer-analysis-parse-content">
                                {subjectParse}
                            </div>
                        </div>
                    )}
                </div>
            </div>
        </Spin>
    );
};

export default AnswerAnalysis;
